package com.kkb.robotcustomerservice.controller;

import com.kkb.robotcustomerservice.util.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/uploadPic")
@CrossOrigin
public class UploadPicController {



    /**
     *
     * @param pic 图片
     * @param request servlet
     * @return 图片存储地址
     * @throws IOException
     */

    @Value("${upload.path}")
    private String path;


    @RequestMapping(method = RequestMethod.POST)
    public JsonResult<String> doAdd(@RequestParam("pic") MultipartFile pic, HttpServletRequest request) throws IOException {

        JsonResult<String> result = new JsonResult<>();

        //获取路径
        String savePath = path;
        String osPath = "/uploadPic/";



        //处理文件名重复
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + FilenameUtils.getExtension(pic.getOriginalFilename());

        //上传目录
        File savePathDir = new File(savePath);

        if (!savePathDir.exists()) {
            savePathDir.mkdirs();
        }

        //保存文件
        pic.transferTo(new File(savePathDir, fileName));

        result.setData(osPath+fileName);
        result.setSuccess(true);
        result.setMsg("返回数据成功");
        return result;
    }

}
